package com.qiche.controller.wx;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.qiche.model.*;
import com.qiche.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.qiche.aspect.Result;
import com.qiche.dto.MemberSubscribeDetailDto;
import com.qiche.dto.SubscribeDto;
import com.qiche.dto.SubscribeProductDto;
import com.qiche.enums.ResultEnum;
import com.qiche.enums.SubscribeStatusEnum;
import com.qiche.model.Merchant;
import com.qiche.model.Product;
import com.qiche.model.ServiceItemWorkstage;
import com.qiche.model.StoreMember;
import com.qiche.model.Subscribe;
import com.qiche.model.SubscribeConfig;
import com.qiche.model.SubscribeProduct;
import com.qiche.model.Workstage;
import com.qiche.service.MerchantService;
import com.qiche.service.ServiceItemWorkstageService;
import com.qiche.service.SubscribeConfigService;
import com.qiche.service.SubscribeProductService;
import com.qiche.service.SubscribeService;
import com.qiche.service.WorkstageService;
import com.qiche.service.impl.SubscribeServiceImpl;
import com.qiche.util.ApiUtils;
import com.qiche.util.DateTimeUtils;

/**
 * @Author: Linzewen
 * @Date: 2018/5/22 0022 15:26
 */
@RestController
@RequestMapping(value = "wx/subscribe")
public class SubscribeWxController {

	private static final Logger log = LoggerFactory.getLogger(ApiUtils.class);

	@Autowired
	private SubscribeService subscribeService;

	@Autowired
	private MerchantService merchantService;

	@Autowired
	private WorkstageService workstageService;

	@Autowired
	private SubscribeConfigService subscribeConfigService;

	@Autowired
	private ServiceItemWorkstageService serviceItemWorkstageService;

	@Autowired
	private SubscribeProductService subscribeProductService;

	/**
	 * 我的订单 全部预约列表
	 * 
	 * @return
	 */
	@PostMapping("/getList")
	public Result<?> getList(@RequestParam String accessToken, @RequestParam String openid, String unionid,
			@RequestParam Long merchantId, StoreMember storeMember, @RequestParam String status) {
		List<MemberSubscribeDetailDto> memberSubscribeDetailDtos = subscribeService
				.selectAllMemberSubscribe(storeMember, status);
		return Result.createByResultEnum(ResultEnum.SUCCESS, memberSubscribeDetailDtos);
	}

	/**
	 * 用户提交预约 预约保存,并为此门店添加此用户
	 * 
	 * @param
	 * @return
	 */
	@PostMapping("/create")
	public Result<?> createSubscribe(@RequestParam String accessToken, @RequestParam String openid, String unionid,
			@RequestParam Long merchantId, StoreMember storeMember, Long productIds, Long storeMemberCarId,
			Subscribe subscribe, BindingResult result, String subscribeTime) throws Exception {
		subscribe.setCustomerId(storeMember.getId());
		subscribe.setSubscribeStatus((byte) 0);
		subscribe.setSubscribeTime(DateTimeUtils.str2Date(subscribeTime, "yyyy-MM-dd HH:mm"));
		List<Long> productIdsList = new ArrayList<>();
		productIdsList.add(productIds);
		// Collections.addAll(productIdsList, productIds);
		Result<?> result1 = subscribeService.subscribe(subscribe, storeMemberCarId, productIdsList);
		if (result1.isSuccess()) {
			return Result.createByResultEnum(ResultEnum.SUCCESS, subscribe);
		} else {
			return Result.createByResultEnum(ResultEnum.FAILURE);
		}

	}

	/**
	 * 获取预约时间以及预约状态
	 * 
	 * @param day
	 *            2018-05-29
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/querySubscribeDate")
	public Result<?> querySubscribeDate(@RequestParam String accessToken, @RequestParam String openid, String unionid,
			@RequestParam Long merchantId, StoreMember storeMember, @RequestParam String day) throws Exception {
		if (StringUtils.isEmpty(day)) {
			return Result.createByErrorMessage("天数不能为空，默认为今天请入参");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		Calendar calPresent = Calendar.getInstance();
		calPresent.setTime(new Date());
		calPresent.set(Calendar.SECOND, 0);
		calPresent.set(Calendar.MINUTE, 0);
		calPresent.set(Calendar.MILLISECOND, 0);
		Calendar calDate = Calendar.getInstance();
		if (sdfDate.parse(day).getTime() == sdfDate.parse(sdfDate.format(new Date())).getTime()) {
			calDate.setTime(sdf.parse(day + " " + sdfTime.format(calPresent.getTime())));// 门店开店时间
		} else {
			calDate.setTime(sdf.parse(day + " 09:00"));
		}
		int startDate = calDate.get(Calendar.HOUR_OF_DAY);
		calDate.setTime(sdf.parse(day + " 22:00"));// 门店关门时间
		int endDate = calDate.get(Calendar.HOUR_OF_DAY);
		// 阈值config
		SubscribeConfig subscribeConfig = subscribeConfigService.selectByMerchantId(merchantId.intValue());

		Calendar cal = Calendar.getInstance();
		cal.setTime(sdfDate.parse(day));
		cal.set(Calendar.HOUR_OF_DAY, startDate);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		do {// 生成预约时间段
			map.put("time", sdfTime.format(cal.getTime()));
			if(subscribeConfig!=null){
			if (subscribeConfig.getAlwaysStatus()!=null && subscribeConfig.getAlwaysStatus() == 0 ) {
				Integer countSubscribe = subscribeService
						.selectCountByMerchantIdSubscribeTimeStatus(merchantId.intValue(), sdf.format(cal.getTime()));

				if (subscribeConfig.getDegreeLeisure() >= countSubscribe) {
					map.put("status", "1");
				}
				if (subscribeConfig.getDegreeModerate() <= countSubscribe) {
					map.put("status", "2");
				}
				if (subscribeConfig.getDegreeTense() <= countSubscribe) {
					map.put("status", "3");
				}
				if (subscribeConfig.getDegreeHot() <= countSubscribe) {
					map.put("status", "4");
				}
			} else {
				map.put("status", subscribeConfig.getAlwaysStatus() == null ? "1" : subscribeConfig.getAlwaysStatus());// 当前时间的一个火爆状态
			}
			}else{
				map.put("status", "1");
			}
			list.add(map);
			map = new HashMap<>();
			String dateMinut = DateTimeUtils.addDateMinut(sdf.format(cal.getTime()), 30);
			cal.setTime(sdf.parse(dateMinut));
			startDate = cal.get(Calendar.HOUR_OF_DAY);
		} while (startDate <= endDate);
		Map<String, Object> data = new HashMap<>();
		data.put("list", list);
		data.put("date", sdfDate.format(cal.getTime()));
		return Result.createBySuccess("预约时间段", data);

	}

	/**
	 * 取消预约
	 * 
	 * @param subcribeId
	 * @return
	 */
	@PostMapping("/cancel")
	public Result<?> cancelSubscribe(@RequestParam String accessToken, @RequestParam String openid, String unionid,
			@RequestParam Long merchantId, StoreMember storeMember, Long subcribeId) {
		return subscribeService.updateSubscribeStatus(subcribeId, SubscribeStatusEnum.CANCEL.getStatus());
	}

	/**
	 * 根据状态查询预约列表
	 * 
	 * @param status
	 * @return
	 */
	@PostMapping("/getListByStatus")
	public Result<?> getListByStatus(@RequestParam String accessToken, @RequestParam String openid, String unionid,
			@RequestParam Long merchantId, StoreMember storeMember, @RequestParam String status) {
		List<MemberSubscribeDetailDto> memberSubscribeDetailDtos = subscribeService
				.selectSubscribeBysToreMemberAndStatus(storeMember, status);
		return Result.createByResultEnum(ResultEnum.SUCCESS, memberSubscribeDetailDtos);
	}

	/**
	 * 根据ID获取预约详情
	 * 
	 * @param subscribeId
	 * @return
	 */
	@PostMapping("/getDetailById")
	public Result<?> getDetailById(@RequestParam String accessToken, @RequestParam String openid, String unionid,
			@RequestParam Long merchantId, StoreMember storeMember, @RequestParam String subscribeId) {
		Subscribe subscribe = subscribeService.selectByKey(subscribeId);
		if (subscribe == null) {
			return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
		}

		// 获取预约服务信息
		List<Product> products = subscribeProductService.selectProductBySubscribeId(subscribe.getSubscribeId());
		List<SubscribeProductDto> collect = products.stream().map(SubscribeServiceImpl::createSubscribeProductDto)
				.collect(Collectors.toList());
		Double sumPrice = products.stream().map(Product::getPrice).reduce(0.00, Double::sum);
		MemberSubscribeDetailDto memberSubscribeDetailDto = new MemberSubscribeDetailDto();
		Merchant merchant = merchantService.selectById(subscribe.getMerchantId());
		List<Workstage> workstageList = workstageService.selectByItemId(products.get(0).getId());

		List<SubscribeProduct> subscribeProducts = subscribeProductService
				.selectBySubscribeId(subscribe.getSubscribeId());
		List<ServiceItemWorkstage> serviceItemWorkstages = serviceItemWorkstageService
				.selectBySubproId(subscribeProducts.get(0).getSubProId());

		BeanUtils.copyProperties(subscribe, memberSubscribeDetailDto);
		memberSubscribeDetailDto.setPhone(storeMember.getPhone());
		memberSubscribeDetailDto.setUsername(storeMember.getName());
		memberSubscribeDetailDto.setMerchantName(merchant.getName());
		memberSubscribeDetailDto.setWorkstage(workstageList);
		memberSubscribeDetailDto.setItemWorkstages(serviceItemWorkstages);

		memberSubscribeDetailDto.setConsumeTime(products.get(0).getConsumeTime());
		memberSubscribeDetailDto.setSubscribeProductDtos(collect);
		memberSubscribeDetailDto.setPrice(sumPrice);// 订单结束subscribe_status
													// 为2时,生效

		return Result.createByResultEnum(ResultEnum.SUCCESS, memberSubscribeDetailDto);
	}

	/**
	 * 去到预约
	 * 
	 * @param memberCarId
	 * @param merchantId
	 * @return
	 */
	@PostMapping(value = "/toSubscrube")
	public Result<?> toSubscrube(@RequestParam String accessToken, @RequestParam String openid, String unionid,
			@RequestParam Long merchantId, StoreMember storeMember,
			@RequestParam(name = "memberCarId", required = false) Long memberCarId) {
		if (merchantId == null || merchantId <= 0) {
			return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
		}
		SubscribeDto subscribeDto = subscribeService.toSubscribe(storeMember, memberCarId, merchantId);
		return Result.createBySuccess("预约数据查询成功", subscribeDto);
	}

}
